package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.shopping.ICartService;
import com.mall.shopping.dto.CartProductDto;
import com.mall.shopping.dto.ClearCartItemRequest;
import com.mall.shopping.dto.ClearCartItemResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * step5
 * 将购物车中的缓存失效
 */
@Slf4j
@Component
public class ClearCartItemHandler extends AbstractTransHandler {
    @Autowired
    private RedissonClient redissonClient;

    //是否采用异步方式执行
    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        Long userId = createOrderContext.getUserId();
        log.info("将购物车中的缓存失效,userId=" + userId);
        // 清空购物车中已选中的商品
        RMap<Long, List<CartProductDto>> map = redissonClient.getMap(userId.toString());

        List<CartProductDto> list = map.get(userId);

        log.info("清空购物车之前：" + list);

        if (list != null) {

            List<CartProductDto> collect = list.stream().filter(s -> "false".equals(s.getChecked())).collect(Collectors.toList());
            map.put(userId, collect);
            log.info("清空购物车之后：" + list);
        }

        return true;
    }
}
